﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Syndication;
using System.ServiceModel.Web;
using System.Text;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace TfsRssService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "WorkItemFeed" in both code and config file together.
    public class WorkItemFeed : IWorkItemFeed
    {
#if(DEBUG)
        [OperationBehavior(Impersonation = ImpersonationOption.Required)]
#else
        [OperationBehavior(Impersonation = ImpersonationOption.NotAllowed)]
#endif
        public SyndicationFeedFormatter CreateFeed(string projCollection, string proj)
        {
            //bool.Parse(ConfigurationManager.AppSettings["UseImpersonation"])
            if (projCollection == "error")
            {
                //Logger.Write(new LogEntry() { Message = "hello" });

                ExceptionManager exManager = EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>();
                int j = exManager.Process<int>(
                    () =>
                    {
                        if (1 == 1)
                        {
                            throw new WebFaultException<string>(
                        string.Format(Properties.Resources.BadCollectionError, projCollection),
                        System.Net.HttpStatusCode.NotFound);
                        }

                        return 3;
                    }, "Policy 1");
                

                throw new WebFaultException<string>(
                    string.Format(Properties.Resources.BadCollectionError, projCollection),
                    System.Net.HttpStatusCode.NotFound);
            }
            
            // Create a new Syndication Feed.
            SyndicationFeed feed = new SyndicationFeed(string.Format(Properties.Resources.WorkItemFeedDescription, projCollection, proj), string.Format(Properties.Resources.WorkItemFeedDescription, projCollection, proj), null);
            feed.Authors.Add(new SyndicationPerson("testuser@blah.com"));
            //feed.Contributors.Add();
            feed.Categories.Add(new SyndicationCategory("Work Item"));
            feed.ImageUrl = new Uri(@"http://www.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=tfsrss&DownloadId=270362");
            feed.Copyright = new TextSyndicationContent(string.Format("{0} {1}",ConfigurationManager.AppSettings["CopyrightNotice"],DateTime.Now.Year));

            List<SyndicationItem> items = new List<SyndicationItem>();

            // Create a new Syndication Item.
            SyndicationItem item = new SyndicationItem("An item for "+System.Security.Principal.WindowsIdentity.GetCurrent().Name, "Item content", new Uri(@"http://www.bbc.co.uk"));
            items.Add(item);
            feed.Items = items;

            // Return ATOM or RSS based on query string
            // rss -> http://localhost:8732/WorkItems/testCollection/testProject/
            // atom -> http://localhost:8732/WorkItems/testCollection/testProject/?format=atom
            string query = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];
            SyndicationFeedFormatter formatter = null;
            if (query == "atom")
            {
                formatter = new Atom10FeedFormatter(feed);
            }
            else
            {
                formatter = new Rss20FeedFormatter(feed);
            }

            return formatter;
        }
    }
}
